package org.bet.loader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bet.domain.BioFeatureEntry;
import org.bet.io.CustomResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

public class DefaultBioFeatureSetLoader implements BioFeatureSetLoader {
	
	protected final Log logger = LogFactory.getLog(this.getClass());

	private ResourceLoader resourceLoader = new CustomResourceLoader();

	public ResourceLoader getResourceLoader() {
		return resourceLoader;
	}

	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}
	
	/* (non-Javadoc)
	 * @see org.bet.loader.BioFeatureSetLoader#load(java.lang.String[], org.bet.loader.DefaultBioFeatureSetLoader.DropTarget, org.bet.loader.BioFeatureEntryParser)
	 */
	@Override
	public int load(String[] locations, DropTarget dropTarget, BioFeatureEntryParser parser) {
		try{
			int totalEntries = 0;

			if(!ArrayUtils.isEmpty(locations)){
				for(String location : locations){
					
					Resource resource = resourceLoader.getResource(location);
					if(resource != null && resource.isReadable()){
						
						int entryCount = loadResource(resource, dropTarget, parser);
						
						totalEntries += entryCount;
					}
					else{
						logger.warn("Not available resource: " + location);
					}
				}
				
			}
			else{
				logger.warn("Empy resourceLoacations");
			}
			
			return totalEntries;
		}
		catch(Exception e){
			logger.error("Failed to load: " + e);
			throw new RuntimeException("Failed to load: " + e);
		}
	}

	private int loadResource(Resource resource, DropTarget dropTarget, BioFeatureEntryParser parser) throws Exception{
		BufferedReader reader = null;
		int entryCount = 0;
		try{
			reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
			String line = null;	
			while((line = reader.readLine()) != null){ 
				List<BioFeatureEntry> entries = parser.parseEntries(line, dropTarget.getTarget());
				dropTarget.dropEntries(entries);
				entryCount += ((entries != null)? entries.size() : 0);
			}
		}
		finally{
			if(reader != null){
				try { reader.close(); } catch (IOException e) {}
			}
			
		}
		return entryCount;
	}
}
